package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.bean.User;
import com.chen.common.R;
import com.chen.exception.CustomException;
import com.chen.mapper.UserDao;
import com.chen.service.UserService;
import com.chen.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {


    /**
     * 获取验证码
     * @param user
     * @return
     */
    @Override
    public R<String> sendMsg(User user, HttpSession session) {
        String phone = user.getPhone();
        //获取验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        //存入session中
        session.setAttribute(phone,code);
        //方便测试  直接返回前端 自动填充
        return R.success(code);
    }

    /**
     * 登录验证
     * @param
     * @return
     */
    @Override
    public R<String> login(Map<String,Object> map, HttpSession session) {
        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从session中获取手机号和code  和用户输入的进行对比
        Object oldCode = session.getAttribute(phone);
        if (oldCode==null){
            throw new CustomException("验证码已经失效");
        }
        if (!oldCode.toString().equalsIgnoreCase(code)){
            throw new CustomException("验证码错误");
        }
        //查询是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User one = this.getOne(wrapper);
        //不存在新增到数据库
        if (one==null){
            one = new User();
            one.setName("u_"+phone);
            one.setPhone(phone);
            this.save(one);
        }
        //将id存入session中
        session.setAttribute("user",one.getId());
        return R.success("登陆成功");
    }
}
